import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import NProgress from 'nprogress'

const Login = () => import('../views/Login')
const Layout = () => import('../views/layout')
const Home = () => import('../views/layout/Home/Home.vue')
const Catgory = () => import('../views/layout/Catgory/Cataory.vue')
const Cart = () => import('../views/layout/Cart')
const My = () => import('../views/layout/My/My.vue')
const goodsDetail = () => import('../views/layout/goodsDetail/index.vue')
const NotFound = () => import('../component/NotFound.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    // 路由源信息
    meta: {
      title: '登录'
    }
  },
  {
    path: '/detail/:proid',
    name: 'detail',
    component: goodsDetail,
    meta: {
      title: '商品详情'
    }
  },
  {
    path: '/',
    name: 'layout',
    redirect: '/home',
    component: Layout,
    children: [
      {
        path: 'home',
        name: 'home',
        component: Home,
        meta: {
          title: '首页'
        }
      },
      {
        path: 'catgory',
        name: 'catgory',
        component: Catgory,
        meta: {
          title: '商品分类'
        }
      },
      {
        path: 'cart',
        name: 'cart',
        component: Cart,
        meta: {
          title: '购物车'
        }
      },

      {
        path: 'my',
        name: 'my',
        component: My,
        meta: {
          // 代表需要登录才可以跳转
          isNeedLogin: true,
          title: '我的'
        }
      }
    ]
  },
  {
    path: '*',
    component: NotFound
  }

  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 开启加载进度条
  NProgress.start()
  if (to.meta.isNeedLogin) {
    if (store.state.User.token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

// 路由后置守卫
router.afterEach((to, from) => {
  // 关闭加载进度条
  NProgress.done()
  document.title = to.meta.title
})
export default router
